package com.hui.platform.falseworkapi.common.security.utils;

import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import java.util.Objects;

/**
 * @Date 2020/4/21 17:10
 * @Author hui
 **/
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class SecurityUtils {

    /**
     * 密码认证用户
     *
     * @param username           用户名
     * @param password           密码
     * @param userDetailsService 服务
     * @param passwordEncoder    编码器
     * @return GlobalUserDetails
     */
    public static UserDetails authenticate(String username,
                                          String password,
                                          UserDetailsService userDetailsService,
                                          PasswordEncoder passwordEncoder) {
        //获取待认证的信息
        UserDetails userDetails = userDetailsService.loadUserByUsername(username);
        //密码认证
        if (!passwordEncoder.matches(password, userDetails.getPassword())) {
            throw new BadCredentialsException("密码不正确");
        }
        return userDetails;
    }


    /**
     * 设置Request的userType内部
     * code:用户类型
     * //设置用户类型必须在userDetailsService前使用
     */
    public static void setUserType(String code) {
        Objects.requireNonNull(RequestContextHolder.getRequestAttributes())
                .setAttribute("UserType_", code, RequestAttributes.SCOPE_REQUEST);
    }

    /**
     * 获取用户类型字符值
     *
     * @return 用户类型或者null
     */
    public static String getUserType() {
        Object o = Objects.requireNonNull(RequestContextHolder.getRequestAttributes())
                .getAttribute("UserType_", RequestAttributes.SCOPE_REQUEST);
        if (o == null) {
            return "-1";
        }
        return o.toString();
    }
}
